package com.pine.common.redis.config;

import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;

import java.time.Duration;

/**
 * redissonClient 工具类
 *
 * @author pine manage
 * @since 2024-08-22
 */
public class RedissonClientUtil {

    private static RedissonClient redissonClient;

    public static RedissonClient getRedissonClient() {
        init();
        return redissonClient;
    }

    /**
     * 设置缓存
     *
     * @param key               key
     * @param value             value
     * @param timeToLiveSeconds 失效时间(单位：秒)
     */
    public static void setCacheWithExpiration(String key, Object value, long timeToLiveSeconds) {
        init();
        RBucket<Object> bucket = redissonClient.getBucket(key);
        // 设置缓存值和过期时间
        bucket.set(value, Duration.ofSeconds(timeToLiveSeconds));
    }

    /**
     * 设置缓存
     *
     * @param key   key
     * @param value value
     */
    public static void setCache(String key, Object value) {
        init();
        RBucket<Object> bucket = redissonClient.getBucket(key);
        // 设置缓存值
        bucket.set(value);
    }

    /**
     * 获取缓存
     *
     * @param key key
     * @return value
     */
    public static Object getCache(String key) {
        init();
        RBucket<Object> bucket = redissonClient.getBucket(key);
        return bucket.get();
    }

    /**
     * 移除缓存
     *
     * @param key key
     */
    public static void removeCache(String key) {
        init();
        redissonClient.getBucket(key).delete();
    }


    private static void init() {
        if (redissonClient == null) {
            redissonClient = SpringBeanUtil.getByClass(RedissonClient.class);
        }
    }
}
